const config = require("../config.js")
/*
*url    根地址
*params 请求参数
*return 返回任务的Promise
*/

function getRequest(url, params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${url}`,
      data: Object.assign({}, params),
      method: 'GET',
      header: { 'Content-Type': 'json' },//'content-type': 'application/json'  默认值
      success(request) {
        resolve(request.data)
      },
      fail(error) {
        reject(error)
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        })
      }
    })
  })
}

function postRequest(url, params, showLoading = true) {
  if (showLoading) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${url}`,
      data: Object.assign({}, params),
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success(request) {
        if (showLoading) {
          wx.hideLoading()
        }
        if(request.statusCode == 500){
          wx.showToast({
            title: '服务器异常',
            icon:'none'
          })
          reject();
          return false;
        }
        if(request.statusCode == 404){
          wx.showToast({
            title: '请求的资源不存在',
            icon:'none'
          })
          reject();
          return false;
        }
        if(request.statusCode == 200){
          resolve(request.data)
        }
      },
      fail(error) {
        if (showLoading) {
          wx.hideLoading()
        }
        wx.showToast({
          title: '网络异常',
          icon:'none'
        })
        reject("网络异常")
      },
      complete: () => {
       
      }
    })
  })
}


/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}


var list = {
  getRequest,
  postRequest,
  config
};


for (let key in config) {
  list[key + "Post"] = (params, showLoading) => {
    return postRequest(config[key], params, showLoading)
  }
  list[key + "Get"] = (params) => {
    return getRequest(config[key], params)
  }
}

module.exports = list